package www.lagou.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author sjp
 * @date 2021/5/8 13:14
 * @description
 */
public class DruidUtils {
    //1.定义成员变量
    /**
     * 资源链接池
     */
    public static DataSource dataSource;

    //2.静态代码块 设置配置信息
    static {
        try {
            //3.创建属性集对象
            Properties properties = new Properties();

            //Druid连接池不能主动加载配置文件，需要指定文件
            //4.创建输入流 与配置文件建立关联 (加载配置文件)
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

            //5.使用Properties对象的load方法，可以从字节流中读取配置信息
            properties.load(inputStream);

            //6.获取数据连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接对象
     *
     * @return
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 获取连接池对象
     *
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }


    /**
     * 释放连接资源 - DML使用
     *
     * @param connection
     * @param statement
     * @throws SQLException
     */
    public static void close(Connection connection, Statement statement) throws SQLException {
        if (null != statement) {
            statement.close();
        }
        if (null != connection) {
            connection.close();
        }
    }

    /**
     * 释放连接资源 - DQL使用
     *
     * @param connection
     * @param statement
     * @param resultSet
     * @throws SQLException
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (null != resultSet) {
            resultSet.close();
        }
        close(connection, statement);
    }

}
